from sqlalchemy import Boolean, Column, String, Integer, ForeignKey, Table, DateTime
from sqlalchemy.orm import relationship

from app.models.base import Base

# 用户-角色关联表
user_role = Table(
    "user_role",
    Base.metadata,
    Column("user_id", Integer, ForeignKey("user.id"), primary_key=True),
    Column("role_id", Integer, ForeignKey("role.id"), primary_key=True),
)


class User(Base):
    """用户模型"""
    username = Column(String(64), unique=True, index=True, nullable=False)
    email = Column(String(120), unique=True, index=True, nullable=False)
    hashed_password = Column(String(128), nullable=False)
    full_name = Column(String(100), nullable=True)
    is_active = Column(Boolean, default=True)
    is_superuser = Column(Boolean, default=False)
    last_login = Column(DateTime, nullable=True)
    
    # 关系
    roles = relationship("Role", secondary=user_role, back_populates="users")
    
    # 项目关系
    managed_projects = relationship("Project", foreign_keys="Project.manager_id", back_populates="manager")
    created_projects = relationship("Project", foreign_keys="Project.creator_id", back_populates="creator")
    
    # 任务关系
    assigned_tasks = relationship("Task", foreign_keys="Task.assignee_id", back_populates="assignee")
    created_tasks = relationship("Task", foreign_keys="Task.creator_id", back_populates="creator")
    task_comments = relationship("TaskComment", back_populates="user")
    
    # 风险和问题关系
    created_risks = relationship("Risk", foreign_keys="Risk.creator_id", back_populates="creator")
    assigned_risks = relationship("Risk", foreign_keys="Risk.assignee_id", back_populates="assignee")
    created_issues = relationship("Issue", foreign_keys="Issue.creator_id", back_populates="creator")
    assigned_issues = relationship("Issue", foreign_keys="Issue.assignee_id", back_populates="assignee")
    
    # 通知关系
    notifications = relationship("Notification", foreign_keys="Notification.recipient_id", back_populates="recipient")


class Role(Base):
    """角色模型"""
    name = Column(String(64), unique=True, index=True, nullable=False)
    description = Column(String(255), nullable=True)
    
    # 关系
    users = relationship("User", secondary=user_role, back_populates="roles")
    permissions = relationship("Permission", back_populates="role")


class Permission(Base):
    """权限模型"""
    name = Column(String(64), unique=True, index=True, nullable=False)
    description = Column(String(255), nullable=True)
    resource = Column(String(64), nullable=False)  # 资源类型，如project, task等
    action = Column(String(64), nullable=False)  # 操作类型，如create, read, update, delete等
    
    # 关系
    role_id = Column(Integer, ForeignKey("role.id"), nullable=False)
    role = relationship("Role", back_populates="permissions")